<template>
  <div>
    <Modal
      :value="modalState"
      :title="title"
      :loading="loading"
      ok-text="保存"
      @on-ok="handleSubmit"
      @on-cancel="cancel"
      width="35%">
      <Form
        ref="productListModal"
        :model="row"
        :rules="rules"
        style="width: 100%; margin-left: 50px;"
        :label-width="100">
        <FormItem prop="name" label="商品名称：" style="width: 300px">
          <Input type="text" v-model="row.name" placeholder="请输入商品名称" />
        </FormItem>
        <FormItem prop="price" label="参考价格：" style="width: 300px">
          <Input type="text" v-model="row.price" placeholder="请输入参考价格" />
        </FormItem>
        <FormItem prop="des" label="备注：" style="width: 400px">
          <Input type="textarea" :rows="4" v-model="row.des" placeholder="请输入备注" />
        </FormItem>
        <!-- <FormItem prop="state" label="是否开启：" style="width: 400px">
          <i-switch v-model="row.openState" style="margin-left: 30px;" />
        </FormItem> -->
      </Form>
    </Modal>
  </div>
</template>
<script>
import {
  mapActions,
  mapState
} from 'vuex'
export default {
  name: 'ProductListModal',
  data () {
    const reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
    const validateMoney = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('金额不能为空!'))
      } else {
        if (!reg.test(value)) {
          callback(new Error('请输入正确的金额！'))
        } else {
          callback()
        }
      }
    }

    return {
      title: '',
      loading: true,
      rules: {
        name: [
          {
            required: true,
            message: '商品名称不能为空',
            trigger: 'blur'
          }
        ],
        price: [
          {
            validator: validateMoney,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  updated () {
    if (this.row.id && this.row.id !== '') {
      this.title = '编辑商品'
    } else {
      this.title = '添加商品'
    }
  },
  computed: {
    ...mapState({
      row: state => state.goodService.row,
      modalState: state => state.modal.modalState
    })
  },
  methods: {
    ...mapActions(['updateModalState']),
    changeLoading () {
      this.loading = false
      this.$nextTick(() => {
        this.loading = true
      })
    },
    handleSubmit () {
      this.$refs.productListModal.validate((valid) => {
        if (!valid) {
          return this.changeLoading()
        }
        this.$emit('product-list-valid', {
          id: this.row.id,
          name: this.row.name,
          price: this.row.price,
          des: this.row.des
          // state: this.row.openState === true ? 0 : 1
        })
      })
    },
    cancel () {
      this.updateModalState(false)
      this.$refs['productListModal'].resetFields()
    }
  }
}
</script>
